package com.controller;

import com.dao.BabyExchangeDao;
import com.dao.BabyGoodsDao;
import com.dao.BabyWellDao;
import com.entity.BabyExchangeDO;
import com.entity.BabyGoodsDO;
import com.entity.BabyWellDO;
import com.entity.dto.BabyGoodsDTO;
import com.entity.dto.IndexGoodsDTO;
import com.util.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Author：hanll
 * ClassName：BabyGoodsController
 * Date：2022/10/22 19:41
 * Version：1.0
 * Description：
 */
@RequestMapping("/v1/api/goods")
@RestController
@CrossOrigin
public class BabyGoodsController {

    @Resource
    private BabyGoodsDao babyGoodsDao;

    @Resource
    private BabyWellDao babyWellDao;

    @Resource
    private BabyExchangeDao babyExchangeDao;

    @Value("${image.path}")
    private String imagePath;

    @Value("${dir.sep}")
    private String dirSep;

    @Value("${server.nginx}")
    private String serverNginx;

    @Value("${server.nginx.son}")
    private String serverNginxSon;

    @GetMapping("/list")
    public Result find(String lpm) {
        try {
            Specification<BabyGoodsDO> specification = (root, query, cb) -> {
                Predicate predicate = cb.conjunction();
                if (lpm != "" && lpm != null) {
                    predicate.getExpressions().add(cb.like(root.get("lpm"), "%" + lpm + "%"));
                }
                return predicate;
            };
            List<BabyGoodsDO> list = babyGoodsDao.findAll(specification);
            for (BabyGoodsDO babyGoodsDO : list) {
                if (babyGoodsDO.getLpdz() != null && babyGoodsDO.getLpdz() != "") {
                    babyGoodsDO.setLpdz(babyGoodsDO.getLpdz().replace(imagePath, serverNginx));
                }
            }
            return Result.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询礼品失败");
        }
    }

    /**
     * @Author：hanll
     * @Description：首页打开查询商品
     * @Date：2022-10-22 19:53:54
     * @return：com.util.Result
     **/
    @GetMapping("/index")
    public Result findIndexDate() {
        try {
            IndexGoodsDTO indexGoodsDTO = new IndexGoodsDTO();
            List<BabyGoodsDO> imageDataList = new ArrayList<>();
            List<BabyGoodsDO> imageOtherList = new ArrayList<>();
            List<BabyGoodsDO> babyGoodsDaoAll = babyGoodsDao.findAll();
            for (BabyGoodsDO babyGoodsDO : babyGoodsDaoAll) {
                if (babyGoodsDO.getZt().equals("1")) {
                    if (babyGoodsDO.getLpdz() != null && babyGoodsDO.getLpdz() != "") {
                        babyGoodsDO.setLpdz(babyGoodsDO.getLpdz().replace(imagePath, serverNginx));
                    }
                    imageDataList.add(babyGoodsDO);
                } else {
                    if (babyGoodsDO.getLpdz() != null && babyGoodsDO.getLpdz() != "") {
                        babyGoodsDO.setLpdz(babyGoodsDO.getLpdz().replace(imagePath, serverNginx));
                    }
                    imageOtherList.add(babyGoodsDO);
                }
            }
            indexGoodsDTO.setImageDataList(imageDataList);
            indexGoodsDTO.setImageOtherList(imageOtherList);
            return Result.success(indexGoodsDTO);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("首页打开查询礼品失败");
        }
    }

    @GetMapping("/details/{id}")
    public Result findDetails(@PathVariable String id) {
        try {
            Optional<BabyGoodsDO> optional = babyGoodsDao.findById(id);
            if (!optional.isPresent()) {
                return Result.error("该礼品为空");
            }
            BabyGoodsDO babyGoodsDO = optional.get();
            BabyGoodsDTO babyGoodsDTO = new BabyGoodsDTO();
            BeanUtils.copyProperties(babyGoodsDO, babyGoodsDTO);
            if (babyGoodsDO.getLpdz() != null && babyGoodsDO.getLpdz() != "") {
                String[] suffix = babyGoodsDO.getLpdz().split("/");
                babyGoodsDTO.setTpm(suffix[suffix.length-1]);
                babyGoodsDTO.setLpdz(babyGoodsDO.getLpdz().replace(imagePath, serverNginx));
            }
            return Result.success(babyGoodsDTO);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询礼品详情失败");
        }
    }

    @GetMapping("/exchange/{id}")
    public Result exchange(@PathVariable String id) {
        try {
            Optional<BabyGoodsDO> optional = babyGoodsDao.findById(id);
            if (!optional.isPresent()) {
                return Result.error("该礼品为空");
            }
            BabyGoodsDO babyGoodsDO = optional.get();
            List<BabyWellDO> list = babyWellDao.findAll();
            BabyWellDO wellDO = list.get(0);
            if (wellDO.getJf() != null && wellDO.getJf() > 0) {
                if (wellDO.getJf() >= babyGoodsDO.getSxjf()) {
                    BabyExchangeDO babyExchangeDO = new BabyExchangeDO();
                    babyExchangeDO.setLpbh(id);
                    babyExchangeDO.setDhsj(Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
                    babyExchangeDao.save(babyExchangeDO);
                    wellDO.setJf(wellDO.getJf()-babyGoodsDO.getSxjf());
                    babyWellDao.save(wellDO);
                } else {
                    return Result.error("积分不足");
                }
            } else {
                return Result.error("您的积分为" + wellDO.getJf());
            }
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询礼品详情失败");
        }
    }

    @PostMapping("/edit")
    public Result editGoods(@RequestParam Map<String,String> map, @RequestParam("file") MultipartFile [] file) {
        try {
            if (map != null) {
                BabyGoodsDO babyGoodsDO = new BabyGoodsDO();
                babyGoodsDO.setId(map.get("id"));
                babyGoodsDO.setLpm(map.get("lpm"));
                babyGoodsDO.setSxjf(Integer.parseInt(map.get("sxjf")));
                babyGoodsDO.setZt(map.get("zt"));
                if (file.length > 0) {
                    String fileName = file[0].getOriginalFilename();
                    byte[] bytes = file[0].getBytes();
                    String path = (imagePath+serverNginxSon+dirSep+fileName).replace("/", dirSep);
                    File fe = new File(path);
                    if (!fe.exists() && fe.createNewFile()) {
                        InputStream inputStream = file[0].getInputStream();
                        FileOutputStream fileOutputStream = new FileOutputStream(fe);
                        while(inputStream.read(bytes, 0, bytes.length) != -1) {
                            fileOutputStream.write(bytes);
                        }
                        babyGoodsDO.setLpdz(path.replace(dirSep, "/"));
                    } else {
                        return Result.error("文件存在");
                    }
                } else {
                    String lpdz = map.get("lpdz");
                    String[] split = lpdz.split("/");
                    lpdz = lpdz.replace(map.get("lpdz"), imagePath+serverNginxSon);
                    lpdz += "/" + split[split.length-1];
                    babyGoodsDO.setLpdz(lpdz);
                }
                babyGoodsDao.save(babyGoodsDO);
            }
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("编辑礼品失败");
        }
    }

    @PostMapping("/add")
    public Result addGoods(@RequestParam Map<String,String> map, @RequestParam("file") MultipartFile [] file) {
        try {
            if (map != null) {
                BabyGoodsDO babyGoodsDO = new BabyGoodsDO();
                babyGoodsDO.setLpm(map.get("lpm"));
                babyGoodsDO.setSxjf(Integer.parseInt(map.get("sxjf")));
                babyGoodsDO.setZt(map.get("zt"));
                if (file.length > 0) {
                    String fileName = file[0].getOriginalFilename();
                    byte[] bytes = file[0].getBytes();
                    String path = (imagePath+serverNginxSon+dirSep+fileName).replace("/", dirSep);
                    File fe = new File(path);
                    if (!fe.exists() && fe.createNewFile()) {
                        InputStream inputStream = file[0].getInputStream();
                        FileOutputStream fileOutputStream = new FileOutputStream(fe);
                        while(inputStream.read(bytes, 0, bytes.length) != -1) {
                            fileOutputStream.write(bytes);
                        }
                        babyGoodsDO.setLpdz(path.replace(dirSep, "/"));
                    } else {
                        return Result.error("文件存在");
                    }
                }
                babyGoodsDao.save(babyGoodsDO);
            }
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("新增礼品失败");
        }
    }
}
